﻿
using JMS;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace CheckIn
{
    public class BaseController<T> : MicroServiceControllerBase 
        where T : Way.EntityDB.DBContext
    {
        T _CurrentDBContext;
        /// <summary>
        /// 当前线程的DBContext对象
        /// </summary>
        public T CurrentDBContext
        {
            get
            {
                if (_CurrentDBContext == null)
                {
                    _CurrentDBContext = this.ServiceProvider.GetService<T>();
                    _CurrentDBContext.AutoBeginTransaction = true;
                }
                return _CurrentDBContext;
            }
        }

        long? _UserId;
        public long UserId
        {
            get
            {
                if (this.UserContent == null)
                    return 0;
               
                return _UserId??=long.Parse(this.UserContent.FindFirst("userId").Value);
            }
        }

        public override bool OnInvokeError(string actionName, object[] parameters, Exception error)
        {
            base.OnInvokeError(actionName, parameters, error);

            if (error is ServiceException)
                return true; // return true表示不用生成日志

            return false;
        }

        public override void OnAfterAction(string actionName, object[] parameters)
        {
            base.OnAfterAction(actionName, parameters);

            if (CurrentDBContext.CurrentTransaction != null)
            {
                this.TransactionControl = new JMS.TransactionDelegate(this, (IStorageEngine)CurrentDBContext);
            }
        }

    }
}
